package com.ajaxjs.user.password;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class ClientSide extends Password {
	/**
	 * 
	 * @param realPassword
	 *            明文密码
	 * @return 加密结果
	 */
	public String encryptedPassword(String realPassword) {
		String hashedPassword = getSHA1(realPassword), salted = getSalt() + hashedPassword;

//		System.out.println("hashedPassword:" + hashedPassword);
//		System.out.println("salted:" + salted);
		return Encryption.AES_Encrypt(salted, getAesKey());
	}

	/**
	 * 外界调用的主要工厂方法
	 * 
	 * @param realPassword
	 *            明文密码
	 * @param aesKey
	 *            AES 密钥
	 * @return 加密结果
	 */
	public static String getEncryptedPassword(String realPassword, String aesKey) {
		ClientSide cs = new ClientSide();
		cs.setSalt(cs.passwordGenerator());
		cs.setAesKey(aesKey);

		return cs.encryptedPassword(realPassword);
	}

	static final char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

	/**
	 * SHA1 哈希
	 * 
	 * @param str
	 * @return
	 */
	public static String getSHA1(String str) {
		if (null == str || 0 == str.length())
			return null;

		try {
			MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
			mdTemp.update(str.getBytes(StandardCharsets.UTF_8));

			byte[] md = mdTemp.digest();
			int j = md.length;
			char[] buf = new char[j * 2];
			int k = 0;

			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
				buf[k++] = hexDigits[byte0 & 0xf];
			}

			return new String(buf);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}

		return null;
	}
}
